#pragma once

#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <iostream>
#include <unistd.h>
#include <memory>
#include <string>
#include <cstring>
#include "InetAddr.hpp"

const int gbacklog = 8;
class Socket;
using SockPtr = std::shared_ptr<Socket>;

enum
{
    SOCK_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR,
    ACCEPT_ERROR,
};

// 模板方法模式
class Socket
{
public:
    virtual void CreateSocket() = 0;                                // Socket
    virtual void CreateBind(uint16_t port) = 0;                     // bind
    virtual void CreateListen(const int backlog = gbacklog) = 0;    // listen
    virtual SockPtr CreateAccept(InetAddr *ClientAddr) = 0;         // accept
    virtual bool Connect(const std::string &ip, uint16_t port) = 0; // connect

    virtual int Sockfd() = 0;
    virtual void Close() = 0;

    virtual ssize_t Recv(std::string *out) = 0;
    virtual ssize_t Send(const std::string &in) = 0;

public:
    void BuildListenSocket(uint16_t port) // Server
    {
        CreateSocket();
        CreateBind(port);
        CreateListen();
    }

    bool BuildClientSocket(const std::string &ip, uint16_t port) // Client
    {
        CreateSocket();
        return Connect(ip, port);
    }
};

class TcpSocket : public Socket
{
public:
    TcpSocket()
    {
    }
    TcpSocket(int sockfd)
        : _sockfd(sockfd)
    {
    }

    void CreateSocket() override
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            std::cout << "Sockfd create fail" << std::endl;
            exit(SOCK_ERROR);
        }
        std::cout << "Sockfd create success" << std::endl;
    }

    void CreateBind(uint16_t port) override
    {
        struct sockaddr_in local;
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_family = AF_INET;
        local.sin_port = htons(port); // 转网络序列

        int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            std::cout << "Bind error" << std::endl;
            exit(BIND_ERROR);
        }
        std::cout << "Bind success" << std::endl;
    }

    void CreateListen(int backlog) override
    {
        if (::listen(_sockfd, backlog))
        {
            std::cout << "listen error" << std::endl;
            exit(LISTEN_ERROR);
        }
        std::cout << "listen success" << std::endl;
    }

    SockPtr CreateAccept(InetAddr *clientAddr) override
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        int sockfd = ::accept(_sockfd, (sockaddr *)&client, &len);
        if (sockfd < 0)
        {
            std::cout << "Accept error" << std::endl;
            exit(ACCEPT_ERROR);
        }
        std::cout << "Accept success" << std::endl;

        *clientAddr = InetAddr(client);
        printf("get a new link, client info : %s, sockfd is : %d\n", clientAddr->Addrstr().c_str(), sockfd);
        return std::make_shared<TcpSocket>(sockfd);
    }

    bool Connect(const std::string &ip, uint16_t port) override
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        ::inet_pton(AF_INET, ip.c_str(), &server.sin_addr);
        socklen_t len = sizeof(server);
        int n = ::connect(_sockfd, (sockaddr *)&server, len);
        if (n < 0)
        {
            std::cout << "Connect error" << std::endl;
            return false;
        }
        return true;
    }

    int Sockfd() override
    {
        return _sockfd;
    }

    void Close() override
    {
        if (_sockfd > 0)
            ::close(_sockfd);
    }

    ssize_t Recv(std::string *out) override
    {
        char buffer[4096];
        int n = recv(_sockfd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            *out += buffer;
        }
        return n;
    }

    ssize_t Send(const std::string &in) override
    {
        return ::send(_sockfd, in.c_str(), in.size(), 0);
    }

    ~TcpSocket()
    {
    }

private:
    int _sockfd; // listen or not
};